//
//  KFWMessageInputView.m
//  KWNClient
//
//  Created by 孔六五 on 15/1/5.
//  Copyright (c) 2015年 张明磊. All rights reserved.
//

#import "KFWMessageInputView.h"


#undef  HeightOptions
#define HeightOptions 60

#undef  HeightTextViewOriginal
#define HeightTextViewOriginal 30

#undef  HeightTextViewAdd
#define HeightTextViewAdd 14



@interface KFWRecordTouchButton : UIButton
@property (nonatomic, weak) KFWMessageInputView *messageInputView;
@end


@implementation KFWMessageInputView

@synthesize messageTextView;
@synthesize startRecordTouchButton;
@synthesize inputBackgroundView;
@synthesize delegate;
@synthesize input;
@synthesize button_showOtherOptions;
@synthesize button_send;
@synthesize button_camera;
@synthesize button_photo;
@synthesize view_Options;
@synthesize view_inputTop;
@synthesize view_inputOut;
@synthesize arr_imageDatafilePath;
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = frame;
    }
    return self;
}

+ (KFWMessageInputView *)creatKFWMessageInputViewWithFrame:(CGRect)inputframe delegate:(UIViewController <KFWMessageInputViewDelegate>*)delegate
{
    KFWMessageInputView *inputView = [[self alloc] initWithFrame:inputframe];
    inputView.delegate = delegate;
    inputView.arr_imageDatafilePath = [[NSMutableArray alloc] init];
    [inputView creatSubViewsWithSelfFrame:inputframe];
    [inputView showWithInput:KFWMessageInputNone andMessageInputView:inputView];
    [inputView showView];
    if (inputView.delegate != nil &&[inputView.delegate respondsToSelector:@selector(inputHeightChange:height:)]) {
        [inputView.delegate inputHeightChange:inputView height:HeightInputTop];
    }
    return inputView;
}

- (void)creatSubViewsWithSelfFrame:(CGRect)frame
{
    inputBackgroundView = [[UIView alloc] initWithFrame:frame];
    inputBackgroundView.backgroundColor = [UIColor clearColor];
    [inputBackgroundView setTapActionWithTarget:self selector:@selector(viewResignFirstResponder)];
    inputBackgroundView.userInteractionEnabled = NO;
//    [self addSubview:inputBackgroundView];
    
    //加号按钮
    button_showOtherOptions = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_showOtherOptions setBackgroundImage:[UIImage imageFileName:@"btn_0ptions.png"] forState:UIControlStateNormal];
    button_showOtherOptions.hidden = YES;
    button_showOtherOptions.frame = CGRectMake(10, (HeightInputTop - 30)/2, 30, 30);
    button_showOtherOptions.titleLabel.font = FontOfHelveticaBold(15);
    
    //发送按钮
    button_send = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_send setBackgroundImage:[UIImage imageFileName:@"btn_fasong.png"] forState:UIControlStateNormal];
    button_send.frame = CGRectMake(MainScreenWidth - 10 - 50, (HeightInputTop - 30)/2, 50, 30);
    button_send.titleLabel.font = FontOfHelveticaBold(15);
    [button_send addTarget:self action:@selector(sendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //输入框
    //    messageTextView = [[UITextView alloc] initWithFrame:CGRectMake(10 + button_showOtherOptions.frame.size.width + 10, (HeightInputTop - 30)/2, MainScreenWidth - 10*4 - button_send.frame.size.width - button_showOtherOptions.frame.size.width, 30)];
    messageTextView = [[UITextView alloc] initWithFrame:CGRectMake(10 , (HeightInputTop - 30)/2, MainScreenWidth - 10*3 - button_send.frame.size.width, 30)];
    messageTextView.layer.cornerRadius = 5;
    messageTextView.layer.borderWidth = 0.5;
    messageTextView.layer.borderColor = RGB(190, 190, 190).CGColor;
    messageTextView.font = [UIFont systemFontOfSize:14];
    messageTextView.delegate = self;
    
    //
    view_inputTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, HeightInputTop)];
    view_inputTop.backgroundColor = [UIColor whiteColor];
    [view_inputTop addSubview:messageTextView];
    [view_inputTop addSubview:button_send];
    [view_inputTop addSubview:button_showOtherOptions];
    
    CALayer *layer = [[CALayer alloc] init];
    layer.frame = CGRectMake(0, 0, view_inputTop.frame.size.width, 1);
    layer.borderColor = RGB(183, 186, 188).CGColor;
    layer.borderWidth = 1;
    [view_inputTop.layer addSublayer:layer];
    
    view_Options = [[UIView alloc] initWithFrame:CGRectMake(0, view_inputTop.frame.size.height, frame.size.width, HeightOptions)];
    view_Options.backgroundColor = [UIColor whiteColor];
    
    button_photo = [UIUtils creatButtonAddAction:@selector(photoBtnClick:) andTarget:self];
    button_photo.frame = CGRectMake(10, 10, 40, 40);
    button_photo.backgroundColor = [UIColor blueColor];
    
    button_camera = [UIUtils creatButtonAddAction:@selector(cameraBtnClick:) andTarget:self];
    button_camera.frame = CGRectMake(60, 10, 40, 40);
    button_camera.backgroundColor = [UIColor redColor];
    [view_Options addSubview:button_photo];
    [view_Options addSubview:button_camera];
    
    view_inputOut = [[UIView alloc]initWithFrame:CGRectMake(0, frame.size.height - HeightInputTop, frame.size.width, HeightInputTop)];
    [view_inputOut addSubview:view_inputTop];
    [view_inputOut addSubview:view_Options];

//    [self addSubview:view_inputOut];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        CGRect keyboard = [((NSValue *)[note.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]) CGRectValue];
        [self showWithInput:KFWMessageInputKeyboard andMessageInputView:self];
        [self changeUIWithKeyboardFrame:keyboard];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self changeUIWithKeyboardFrame:CGRectZero];
    }];
}

- (void)showWithInput:(KFWMessageInput)aInput andMessageInputView:(KFWMessageInputView *)ainputview
{
    ainputview.input = aInput;
    
    [ainputview.delegate.view addSubview:inputBackgroundView];
    [ainputview.delegate.view addSubview:view_inputOut];

    switch (aInput) {
        case KFWMessageInputKeyboard:
        {
            ainputview.inputBackgroundView.hidden = NO;
            ainputview.inputBackgroundView.userInteractionEnabled = YES;
            ainputview.view_Options.hidden = YES;

        }
            break;
        case KFWMessageInputNone:
        {
            ainputview.inputBackgroundView.hidden = YES;
            ainputview.inputBackgroundView.userInteractionEnabled = NO;
            ainputview.view_Options.hidden = YES;
            
        }
            break;
        case KFWMessageInputOptions:
        {
            ainputview.inputBackgroundView.hidden = NO;
            ainputview.inputBackgroundView.userInteractionEnabled = YES;
            ainputview.view_Options.hidden = NO;

        }
            break;
        case KFWMessageInputSend:
        {}
            break;
        case KFWMessageInputVoice:
        {}
            break;

        default:
            break;
    }
}

//显示出来的frame
- (void)showView
{
    CGFloat height = 0;
    switch (self.input) {
        case KFWMessageInputKeyboard:
        {
            //键盘在changeUIWithKeyboardFrame更改高度
        }
            break;
        case KFWMessageInputNone:
        {
            height = view_inputTop.frame.size.height;
        }
            break;
        case KFWMessageInputOptions:
        {
            height = view_inputTop.frame.size.height + HeightOptions;

        }
            break;
        case KFWMessageInputSend:
        {}
            break;
        case KFWMessageInputVoice:
        {}
            break;
            
        default:
            break;
    }

    [UIView animateWithDuration:0.3 animations:^{
        [view_inputOut setFrame:CGRectMake(0, self.frame.size.height - height, self.frame.size.width, height)];
    }];

}

//根据键盘变化修改UI
- (void)changeUIWithKeyboardFrame:(CGRect)frame
{
    CGFloat height = 0;
    CGFloat keyboardHeight = frame.size.height;
    height = keyboardHeight + view_inputTop.frame.size.height;
    
    [UIView animateWithDuration:0.3 animations:^{
        [view_inputOut setFrame:CGRectMake(0, self.frame.size.height - height, self.frame.size.width, height)];
    }];
    
    if (delegate != nil && [delegate respondsToSelector:@selector(inputHeightChange:height:)])
    {
        [delegate inputHeightChange:self height:height];
    }
}

//还原起始状态
- (void)viewResignFirstResponder
{
    [messageTextView resignFirstResponder];
    [self textViewDidChange:messageTextView];
    [self showWithInput:KFWMessageInputNone andMessageInputView:self];
    [self showView];
}

//加号按钮
- (void)showOtherOptionsBtnClick:(id)sender
{
    [messageTextView resignFirstResponder];
    [self showWithInput:KFWMessageInputOptions andMessageInputView:self];
    [self showView];
}

//发送按钮
- (void)sendBtnClick:(id)sender
{
    if (messageTextView.text == nil || messageTextView.text.length == 0) {
        if (arr_imageDatafilePath.count > 0) {
            if (self.delegate != nil && [self.delegate respondsToSelector:@selector(sendText:)]) {
                [self.delegate sendText:self];
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"发送的信息为空" duration:1.5];
        }
    }
    else
    {
        if (self.delegate != nil && [self.delegate respondsToSelector:@selector(sendText:)]) {
            [self.delegate sendText:self];
        }
    }
    
}

//相册按钮
- (void)photoBtnClick:(id)sender
{
    
}

//相机按钮
- (void)cameraBtnClick:(id)sender
{
    
}

#pragma mark UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    inputBackgroundView.hidden = NO;
    inputBackgroundView.userInteractionEnabled = YES;
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    inputBackgroundView.hidden = YES;
    inputBackgroundView.userInteractionEnabled = NO;
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView;
{
    CGFloat keyboredheight = view_inputOut.frame.size.height - view_inputTop.frame.size.height;
    CGFloat height = 0;
    CGFloat addheight = 0;  //view_inputTop增加的高度
    
    
//    CGSize textViewSize = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, FLT_MAX)];
    height = [UIUtils heightFor:textView.text withFont:textView.font labWidth:textView.frame.size.width];
//    height = textViewSize.height;
    
    if (height < HeightTextViewOriginal) {
        height = HeightTextViewOriginal;
        addheight = 0;
    }
    else
    {
        if (height>HeightTextViewOriginal)
        {
            //最多显示4行
            NSInteger num = (height - HeightTextViewOriginal)/14 + 1;
            
            if (num <= 3) {
                height = HeightTextViewOriginal + HeightTextViewAdd * num;
                addheight = HeightTextViewAdd * num;
            }
            else
            {
                height = HeightTextViewOriginal + HeightTextViewAdd * 3;
                addheight = HeightTextViewAdd * 3;
            }
        }
    }
    
    [textView setFrameHeight:height];
    [view_inputTop setFrameHeight:addheight + HeightInputTop];
    [button_send setFrameTop:(view_inputTop.frame.size.height - 30)/2];
    [button_showOtherOptions setFrameTop:(view_inputTop.frame.size.height - 30)/2];
    
    [view_inputOut setFrame:CGRectMake(view_inputOut.frame.origin.x, self.frame.size.height - keyboredheight - view_inputTop.frame.size.height, view_inputOut.frame.size.width, keyboredheight + view_inputTop.frame.size.height)];
    
    if (delegate != nil && [delegate respondsToSelector:@selector(inputHeightChange:height:)])
    {
        [delegate inputHeightChange:self height:view_inputOut.frame.size.height];
    }
}

@end

@implementation KFWRecordTouchButton

@synthesize messageInputView;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{}

@end
